import {Component, Input, EventEmitter, OnInit, Output} from '@angular/core';
import {BaseService} from "../../../shared/service/base.service";
import {ApiUrl} from "../../../config/api-url";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzUploadFile} from "ng-zorro-antd/upload";
import {Consts} from "../../../config/consts";

@Component({
  selector: 'app-agency-configuration',
  templateUrl: './agency-configuration.component.html',
  styleUrls: ['./agency-configuration.component.less']
})
export class AgencyConfigurationComponent implements OnInit {
  @Input() isVisible = false;
  @Output()
  emit = new EventEmitter();
  @Input()
  item: any;
  isOkLoading: any;
  dockingStatus: any;
  cardStatus: any;
  customLogo: boolean;
  devicePayeeAccountList: [];
  payeeUserId: any;

  // 图片上传地址
  uploadUrl = ApiUrl.FileUrl + "/uploadImage";
  accessToken = 'bearer ' + sessionStorage.getItem(Consts.ACCESS_TOKEN);
  // 访问服务器图片地址
  serverFileUrl: any;

  pcLogoFileName: any;
  mobileLogoFileName: any;
  pcLogoFileNameLoading = false;
  mobileLogoFileNameLoading = false;

  constructor(private baseService: BaseService, private msg: NzMessageService) {
  }

  ngOnInit(): void {
    this.findDevicePayeeAgency();
    this.findBackEndUrl();
  }

  ngOnChanges() {
    if (this.item != null){
      this.dockingStatus = this.item.dockingStatus;
      this.cardStatus = this.item.cardStatus;
      this.customLogo = this.item.customLogo;
      this.payeeUserId = this.item.payeeUserId;
      this.pcLogoFileName = this.item.pcLogoFileName;
      this.mobileLogoFileName = this.item.mobileLogoFileName;
    }
  };

  // 上传图片
  handleChange(info: any, name: string): void {
    if (info.file.response?.msg) {
      this.baseService.layer.messageWarning(info.file.response?.msg);
      return;
    }
    switch (info.file.status) {
      case 'uploading':
        this.baseService.layer.messageWarning('上传中');
        switch (name) {
          case 'pcLogoFileName':
            this.pcLogoFileNameLoading = true;
            break;
          case 'mobileLogoFileName':
            this.mobileLogoFileNameLoading = true;
            break;
        }
        break;
      case 'done':
        // tslint:disable-next-line:no-non-null-assertion
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          let value = info.file.response.data.keyRes;
          this.baseService.layer.messageSuccess('上传成功');
          switch (name) {
            case 'pcLogoFileName':
              this.pcLogoFileName = value;
              this.pcLogoFileNameLoading = false;
              this.updateCustomLogo({id:this.item.id, pcLogoFileName: this.pcLogoFileName, type: 2})
              break;
            case 'mobileLogoFileName':
              this.mobileLogoFileName = value;
              this.mobileLogoFileNameLoading = false;
              this.updateCustomLogo({id:this.item.id, mobileLogoFileName: this.mobileLogoFileName, type: 3})
              break;
          }
        });
        break;
      case 'error':
        this.baseService.layer.messageError('网络错误!稍后重试!');
        break;
    }
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  closeImage(name: string) {
    switch (name) {
      case 'pcLogoFileName':
        this.pcLogoFileName = null;
        break;
      case 'mobileLogoFileName':
        this.mobileLogoFileName = null;
        break;
    }
  }

  img(event) {
    event.stopPropagation();
  }

  findDevicePayeeAgency(){
    this.baseService.get(ApiUrl.DevicePayeeAccountUrl + '/findDevicePayeeAgency').subscribe(res=>{
      if (res.status == 0){
        this.devicePayeeAccountList = res.data;
      }
    });
  }

  handleCancel() {
    this.isVisible = false;
    this.emit.emit(this.isVisible);
  }

  clickDockingStatus(item: any) {
    const title = this.dockingStatus ? '确定要关闭[' + item.agencyNo + ']该机构的对接权限?' : '确定要开启[' + item.agencyNo + ']该机构的对接权限?';
    this.baseService.layer.modalConfirm(title, confirm => {
      if (confirm) {
        this.dockingStatus = this.dockingStatus ? 0 : 1;
        const body = {dockingStatus: this.dockingStatus, id: item.userId};
        this.update(body);
      }
    });
  }

  clickCardStatus(item) {
    const title = this.cardStatus ? '确定要关闭[' + item.agencyNo + ']该机构的卡片管理?' : '确定要开启[' + item.agencyNo + ']该机构的卡片管理?';
    this.baseService.layer.modalConfirm(title, confirm => {
      if (confirm) {
        this.cardStatus = this.cardStatus ? 0 : 1;
        const body = {cardStatus: this.cardStatus, id: item.userId};
        this.update(body);
      }
    });
  }

  clickCustomLogoStatus(item) {
    const title = this.customLogo ? '确定要关闭[' + item.agencyNo + ']该机构的自定义logo?' : '确定要开启[' + item.agencyNo + ']该机构的自定义logo?';
    this.baseService.layer.modalConfirm(title, confirm => {
      if (confirm) {
        this.customLogo = !this.customLogo;
        const body = {customLogo: this.customLogo, id: item.id, type: 1};
        this.updateCustomLogo(body);
      }
    });
  }

  update(body) {
    this.baseService.put(ApiUrl.UserUrl, body).subscribe(data => {
      if (data.status == 0) {
        this.baseService.layer.messageSuccess('操作成功');
      } else {
        this.baseService.layer.messageError('操作失败');
      }
    });
  }

  updateCustomLogo(body) {
    /**
     * type:1、开关，2、PC端logo，3、移动端logo
     */
    this.baseService.put(ApiUrl.AgencyUrl + "/updateCustomLogo", body).subscribe(data => {
      if (data.status == 0) {
        this.baseService.layer.messageSuccess('操作成功');
        if (body.type === 1 && !body.customLogo){
          this.isVisible = false;
          this.emit.emit(this.isVisible);
        }

      } else {
        this.baseService.layer.messageError('操作失败，' + data.msg);
      }
    });
  }

  updateDevicePayeeAccount() {
    this.baseService.layer.modalConfirm('确定要切换[' + this.item.agencyNo + ']该机构购买设备时的收款账号', confirm => {
      if (confirm) {
        const body = {id:  this.item.userId, payeeUserId: this.payeeUserId};
        this.update(body);
      }else{
        // this.payeeUserId = payeeUserId;
      }
    });
  }


  findBackEndUrl() {
    this.baseService.get(ApiUrl.Config + '/findBackEndUrl?type=image').subscribe(
      data => {
        if (data.status == 0) {
          if (data.data == null || data.data.url == null) {
            this.baseService.layer.messageError('找不到地址');
            return;
          }
          this.serverFileUrl = data.data.url;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
}
